package com.zendesk.maxwell.registry;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.zendesk.maxwell.MaxwellConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.Properties;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/12/10 17:35
 * @Description:
 */
public class NacosRegistryService implements IRegistryService {
	static final Logger LOGGER = LoggerFactory.getLogger(NacosRegistryService.class);

	private static final String DEFAULT_CLUSTER = "default";
	private static final String DEFAULT_APPLICATION = "maxwell";
	private static final String PRO_SERVER_ADDR_KEY = "serverAddr";
	private static final String PRO_NAMESPACE_KEY = "namespace";

	private NamingService naming;

	private MaxwellConfig maxwellConfig;

	public NacosRegistryService(MaxwellConfig maxwellConfig) {
		this.maxwellConfig = maxwellConfig;
		try {
			this.naming = NacosFactory.createNamingService(getNamingProperties());
		} catch (NacosException e) {
			LOGGER.error("创建nacos service异常:", e);
		}
	}

	@Override
	public void register(InetSocketAddress address) throws Exception {
		validAddress(address);
		this.naming.registerInstance(DEFAULT_APPLICATION, this.maxwellConfig.nacosRegistryGroup, address.getAddress().getHostAddress(), address.getPort(), DEFAULT_CLUSTER);
	}

	@Override
	public void unregister(InetSocketAddress address) throws Exception {
		this.naming.deregisterInstance(DEFAULT_APPLICATION, this.maxwellConfig.nacosRegistryGroup, address.getAddress().getHostAddress(), address.getPort(), DEFAULT_CLUSTER);
	}

	private void validAddress(InetSocketAddress address) {
		if (address.getHostName() == null || 0 == address.getPort()) {
			throw new IllegalArgumentException("invalid address:" + address);
		}
	}

	private Properties getNamingProperties() {
		Properties properties = new Properties();
		properties.setProperty(PRO_SERVER_ADDR_KEY, this.maxwellConfig.nacosRegistryServerAddr);
		properties.setProperty(PRO_NAMESPACE_KEY, this.maxwellConfig.nacosRegistryNamespace);
		return properties;
	}
}
